package org.lzy.shop.cart

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import kotlinx.coroutines.launch
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.activity.MainActivity
import org.lzy.shop.activity.SubmitOrderActivity
import org.lzy.shop.adapter.CartAdapter
import org.lzy.shop.base.BaseFragment
import org.lzy.shop.databinding.FragmentCartBinding

class FragmentCart : BaseFragment<FragmentCartBinding>(FragmentCartBinding::inflate) {

    private val cartManager by lazy { ShoppingCartManager.getInstance(requireContext()) }
    private val cartAdapter: CartAdapter by lazy {
        CartAdapter(
            emptyList(),
            onItemSelected = { originalPosition, isSelected ->
                lifecycleScope.launch {
                    cartManager.updateItemSelectedState(originalPosition, isSelected)
                    updateCheckoutInfo()
                    // 确保item取消选择时全选框也取消选中
                    if (!isSelected) {
                        // 临时移除监听器，避免触发selectAllItems(false)
                        binding.cbSelectAll.setOnCheckedChangeListener(null)
                        binding.cbSelectAll.isChecked = false
                        // 重新设置监听器
                        binding.cbSelectAll.setOnCheckedChangeListener { _, checked ->
                            lifecycleScope.launch {
                                cartManager.selectAllItems(checked)
                                updateCartList()
                                updateCheckoutInfo()
                            }
                        }
                    }

                }


            },
            onQuantityChanged = { originalPosition, quantity ->
                lifecycleScope.launch {
                    // 更新购物车中的数量
                    cartManager.updateCartItemQuantity(originalPosition, quantity)
                    // 更新Adapter中的数量显示
                    cartAdapter.updateItemQuantity(originalPosition, quantity)
                    updateCheckoutInfo()
                }
            },onItemDeleted = { originalPosition ->
                lifecycleScope.launch {
                    // 从数据库中删除商品
                    cartManager.removeFromCart(originalPosition)
                    // 更新结算信息
                    updateCheckoutInfo()
                    // 如果购物车为空，更新界面状态
                    if (cartManager.isCartEmpty()) {
                        updateCartList()
                    }
                }
            }
        )
    }
    private var isEditMode = false

    override fun initView() {
        // 初始化购物车管理器
        binding.rvCartItems.layoutManager = LinearLayoutManager(requireContext())
        binding.rvCartItems.adapter = cartAdapter

        // 全选按钮点击事件
        binding.cbSelectAll.setOnCheckedChangeListener {
                _, isChecked ->
            lifecycleScope.launch {
                cartManager.selectAllItems(isChecked)
                updateCartList()
                updateCheckoutInfo()
            }
        }

        // 编辑按钮点击事件
        binding.tvEdit.setOnClickListener {
            isEditMode = !isEditMode
            updateEditMode()
        }

        // 结算/删除按钮点击事件
        binding.btnCheckout.setOnClickListener {
            lifecycleScope.launch {
                val selectedCount = cartManager.getSelectedItemCount()
                if (selectedCount <= 0) {
                    return@launch
                }

                if (isEditMode) {
                    // 删除选中的商品
                    val selectedItems = cartManager.getSelectedCartItems()
                    if (selectedItems.isEmpty()) {
                        return@launch
                    }

                    // 从后往前删除，避免位置错乱
                    val selectedPositions = cartManager.getCartItems().indices
                        .filter { cartManager.getCartItems()[it].isSelected }
                        .reversed()

                    // 优化删除逻辑：先记录要删除的位置，然后逐个删除并更新UI
                    val deletedCount = selectedPositions.size
                    val positionsToDelete = selectedPositions.sortedDescending()

                    // 先从数据库删除所有选中项
                    for (position in positionsToDelete) {
                        cartManager.removeFromCart(position)
                    }
                    // 更新UI并显示成功消息
                    updateCartList()
                    updateCheckoutInfo()
                    showSuccessToast("成功删除 $deletedCount 件商品")
                } else {
                    // 结算逻辑
                    val selectedItems = cartManager.getSelectedCartItems()
                    if (selectedItems.isNotEmpty()) {
                        val bundle = Bundle()
                        // 将选中的商品列表转换为JSON字符串传递
                        val gson = Gson()
                        val selectedItemsJson = gson.toJson(selectedItems)
                        bundle.putString(Constant.SELECTED_CART_ITEMS, selectedItemsJson)
                        // 计算总价并传递
                        val totalPrice = cartManager.calculateTotalPrice()
                        bundle.putString(Constant.GOODSPRICE, totalPrice.toString())
                        // 如果只有一个商品，也可以按照原有方式传递单个商品信息，保证向后兼容
                        if (selectedItems.size == 1) {
                            val item = selectedItems[0]
                            bundle.putInt(Constant.GOODID, item.goodsId)
                            bundle.putString(Constant.GOODSTITLE, item.goodsName)
                            bundle.putString(Constant.GOODPIC, item.goodsMainPic)
                            // 构建规格字符串
                            val specBuilder = StringBuilder()
                            item.spec.forEachIndexed { index, spec ->
                                specBuilder.append(spec.name).append("：").append(spec.price)
                                if (index < item.spec.size - 1) {
                                    specBuilder.append(" ")
                                }
                            }
                            bundle.putString(Constant.GOODSSPEC, specBuilder.toString())
                            bundle.putString(Constant.GOODSNUM, item.quantity.toString())
                        }
                        // 启动订单提交页面
                        startActivity(SubmitOrderActivity::class.java, bundle)
                    }
                }

            }

        }

        // 去逛逛按钮点击事件
        binding.btnGoShopping.setOnClickListener {
            // 跳转到首页或商品列表页
            // 获取Activity并切换到HomeFragment
            val mainActivity = activity as? MainActivity
            mainActivity?.let {
                it.binding.viewPager.currentItem = 0 // 切换到HomeFragment（索引为0）
            }
        }
    }

    override fun requestData() {

    }

    override fun initData() {
        // 初始化数据
    }

    override fun allClick() {
        // 处理所有点击事件
    }

    override fun onResume() {
        super.onResume()
        // 刷新购物车数据
        lifecycleScope.launch {
            updateCartList()
            updateCheckoutInfo()
        }
    }

    // 更新购物车列表
    private suspend fun updateCartList() {
        val cartItems = cartManager.getCartItems()
        cartAdapter.updateData(cartItems)

        // 显示/隐藏空购物车提示
        if (cartItems.isEmpty()) {
            binding.llEmptyCart.visibility = View.VISIBLE
            binding.rvCartItems.visibility = View.GONE
            binding.llCheckoutBar.visibility = View.GONE
        } else {
            binding.llEmptyCart.visibility = View.GONE
            binding.rvCartItems.visibility = View.VISIBLE
            binding.llCheckoutBar.visibility = View.VISIBLE
        }

        // 检查是否全选
        checkSelectAll()
    }

    // 更新结算信息
    private suspend fun updateCheckoutInfo() {
        val totalPrice = cartManager.calculateTotalPrice()
        val selectedCount = cartManager.getSelectedItemCount()
        // 获取选中的商品种类数量
        val selectedItemTypesCount = cartManager.getSelectedItemTypesCount()
        val hasSelectedItems = selectedCount > 0
        binding.tvTotalPrice.text = "¥${String.format("%.2f", totalPrice)}"

        if (isEditMode) {
            // 删除模式
            binding.btnCheckout.text = "删除($selectedItemTypesCount)"

            if (hasSelectedItems) {
                // 有选中商品 - 可以点击，红色背景，正常文字颜色
                binding.btnCheckout.isEnabled = true
                binding.btnCheckout.setBackgroundResource(R.drawable.red_shape)
                binding.btnCheckout.setTextColor(getResColor(android.R.color.white))
            } else {
                // 没有选中商品 - 无法点击，红色背景(但透明度降低)，灰色文字
                binding.btnCheckout.isEnabled = false
                binding.btnCheckout.setBackgroundResource(R.drawable.cart_delete_redshape)
                binding.btnCheckout.setTextColor(getResColor(R.color.RIGHT_ARROW_GRAY))
            }
        } else {
            // 结算模式
            binding.btnCheckout.text = "结算($selectedItemTypesCount)"

            if (hasSelectedItems) {
                // 有选中商品 - 可以点击，蓝色背景，正常文字颜色
                binding.btnCheckout.isEnabled = true
                binding.btnCheckout.setBackgroundResource(R.drawable.blue_shape)
                binding.btnCheckout.setTextColor(getResColor(android.R.color.white))
            } else {
                // 没有选中商品 - 无法点击，蓝色背景(但透明度降低)，灰色文字
                binding.btnCheckout.isEnabled = false
                binding.btnCheckout.setBackgroundResource(R.drawable.cart_unselected_blue_shape)
                binding.btnCheckout.setTextColor(getResColor(R.color.RIGHT_ARROW_GRAY))
            }
        }
    }

    // 更新编辑模式
    private  fun updateEditMode() {
        if (isEditMode) {
            binding.tvEdit.text = "完成"
            binding.llTotalPrice.visibility = View.INVISIBLE
        } else {
            binding.tvEdit.text = "编辑"
            binding.llTotalPrice.visibility = View.VISIBLE
        }

        lifecycleScope.launch {
            updateCheckoutInfo()
        }
    }

    // 检查是否全选
    private suspend fun checkSelectAll() {
        val cartItems = cartManager.getCartItems()
        if (cartItems.isEmpty()) {
            binding.cbSelectAll.isChecked = false
            return
        }

        val isAllSelected = cartItems.all { it.isSelected }
        binding.cbSelectAll.isChecked = isAllSelected
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理Adapter资源，避免内存泄漏
        cartAdapter.clear()
    }
}